package com.share.tool.mock.groovy;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

@Slf4j
public class GroovyMain {
    private static GroovyObject groovyInstacnce;
    private static String fileHome;

    static {
        try {
            //获取代码跟路径
            String classPath = new File(GroovyMain.class.getResource("./").getPath()).getAbsolutePath();
            classPath = classPath.replace("target\\classes", "src\\main\\java");
            fileHome = classPath.replace("target\\test-classes", "src\\test\\java");

            //初始化groovy对象
            Class aClass = new GroovyClassLoader().parseClass(new File(fileHome + "\\Groovy.groovy"));
            groovyInstacnce = (GroovyObject) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 仅仅普通java环境,非spring环境
     */
    public static void main(String[] args) throws IOException {
        File file = new File(fileHome + "\\GroovyData.json");
        String param = FileUtils.readFileToString(file);
        Object value = groovyInstacnce.invokeMethod("parseJson", param);
        log.info("groovy执行结果={}", value);
    }
}
